package com.ittest.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ittest.domain.system.SysLog;
import com.ittest.factory.MapperFactory;
import com.ittest.mapper.system.SysLogMapper;
import com.ittest.service.system.SysLogService;
import com.ittest.utils.BeanUtil;
import com.ittest.utils.TransactionUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *     日志管理业务实现层
 */
public class SysLogServiceImpl implements SysLogService {
    /**
     * 查询所有日志信息
     */
    @Override
    public List<SysLog> findAll() {
        SqlSession sqlSession = null;
        List<SysLog> list = null;
        try {
            // 1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 2. 获取Mapper
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 3.调用Dao层操作
            list = mapper.findAll();
            // 日期转字符串
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (SysLog sysLog : list) {
                // 获取日期对象
                Date visitTime = sysLog.getVisitTime();
                // 获取String字段名
                String visitTimeStr = format.format(visitTime);
                // 设置visitTimerStr值
                sysLog.setVisitTimeStr(visitTimeStr);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo findAll(int page, int size) {
        SqlSession sqlSession = null;
        PageInfo pageInfo = null;
        try {
            // 1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 2. 获取Mapper
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 3.调用Dao层操作
            PageHelper.startPage(page, size);
            List<SysLog> all = mapper.findAll();
            // 日期转字符串
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (SysLog sysLog : all) {
                // 获取日期对象
                Date visitTime = sysLog.getVisitTime();
                // 获取String字段名
                String visitTimeStr = format.format(visitTime);
                // 设置visitTimerStr值
                sysLog.setVisitTimeStr(visitTimeStr);
            }
            // 4.分页 获取参数，设置当前页面和每页数据条数
            pageInfo = new PageInfo(all);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 返回分页查询到的数据
        return pageInfo;
    }

    /**
     *  模糊查询
     * @param timeStr
     */
    @Override
    public PageInfo findByTime(int page, int size,String timeStr) {

        // 获取SqlSession
        SqlSession sqlSession = null;
        PageInfo pageInfo = null;
        try{
            // 1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 2. 获取Mapper
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 3.调用Dao层操作
            PageHelper.startPage(page, size);
            // sname非空处理
            if (StringUtils.isNotBlank(timeStr)){
                timeStr = timeStr.replaceAll(" ","");
            }
            // 调用Mapper层
            List<SysLog> all = mapper.findByTime(timeStr);
            // 日期转字符串
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            for (SysLog sysLog : all) {
                // 获取日期对象
                Date visitTime = sysLog.getVisitTime();
                // 获取String字段名
                String visitTimeStr = format.format(visitTime);
                // 设置visitTimerStr值
                sysLog.setVisitTimeStr(visitTimeStr);
            }
            // 4.分页 获取参数，设置当前页面和每页数据条数
            pageInfo = new PageInfo(all);
        }catch (Exception e){
            e.printStackTrace();
        }
        return pageInfo;
    }

    /**
     * 批量删除
     */
    @Override
    public void deleteByIds(String arr) {
        // 声明SqlSession对象
        SqlSession sqlSession = null;
        try {
            // 1. 获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 2. 获取Dao
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 3. 调用Dao层操作
            // 分割字符串
            if (arr != null && arr.length() > 0) {
                String[] ids = arr.split(",");
                mapper.deleteByIds(ids);
            }
            // 4. 提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            // 出异常，回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            // 记录日志
        } finally {
            try {
                // 释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 生成报告
     */
    @Override
    public ByteArrayOutputStream getReport() {
        SqlSession sqlSession = null;
        List<SysLog> list = null;
        try {
            // 获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 获取mapper
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 调用Mapper层操作
            list = mapper.findAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            TransactionUtil.close(sqlSession);
        }

        //1.获取到对应的Excel文件，工作簿文件
        Workbook wb = new XSSFWorkbook();
        //2.创建工作表
        Sheet s = wb.createSheet("日志数据表");
        //设置通用配置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);
        //制作标题
        s.addMergedRegion(new CellRangeAddress(1, 1, 1, 7));
        Row row_1 = s.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("日志数据信息");
        // 创建一个样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);
        // 制作表头
        String[] fields = {
                "ID",
                "访问时间",
                "访问用户",
                "访问IP",
                "资源URL",
                "执行时间（毫秒）",
                "访问方法"
        };
        Row row_2 = s.createRow(2);
        for (int i = 0; i < fields.length; i++) {
            Cell cell_2_temp = row_2.createCell(1 + i); //++
            cell_2_temp.setCellValue(fields[i]);    //++
            cell_2_temp.setCellStyle(cs_field);
        }
        //制作数据区
        int row_index = 0;
        for (SysLog sysLog : list) {
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);
            // ID
            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(sysLog.getId());    //++
            cell_data_1.setCellStyle(cs_field);
            // 访问时间
            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(sysLog.getVisitTime());
            cell_data_2.setCellValue(time);    //++
            cell_data_2.setCellStyle(cs_field);
            // 访问用户
            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(sysLog.getUsername());    //++
            cell_data_3.setCellStyle(cs_field);
            // 访问IP
            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(sysLog.getIp());    //++
            cell_data_4.setCellStyle(cs_field);
            // 资源URL
            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(sysLog.getUrl());    //++
            cell_data_5.setCellStyle(cs_field);
            // 执行时间
            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(sysLog.getExecutionTime());    //++
            cell_data_6.setCellStyle(cs_field);
            // 访问方法
            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(sysLog.getMethod());    //++
            cell_data_7.setCellStyle(cs_field);


        }
        /**
         *  写出
         */
        //将内存中的workbook数据写入到流中
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            wb.write(os);
            wb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return os;
    }

    /**
     * 日志记录
     * @param log
     */
    @Override
    public void save(SysLog log) {
        // 声明SqlSession对象
        SqlSession sqlSession = null;
        try {
            // 1. 获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            // 2. 获取Dao
            SysLogMapper mapper = MapperFactory.getMapper(sqlSession, SysLogMapper.class);
            // 3. 调用Dao层操作
            mapper.save(log);
            // 4. 提交事务
            TransactionUtil.commit(sqlSession);
        } catch (Exception e) {
            // 出异常，回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            // 记录日志
        } finally {
            try {
                // 释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}



